var items_per_page = 10;
var scroll_in_progress = false;
var myScroll;

load_content = function(refresh, next_page) {

    // This is a DEMO function which generates DEMO content into the scroller.
    // Here you should place your AJAX request to fetch the relevant content (e.g. $.post(...))

    setTimeout(function() { // This immitates the CALLBACK of your AJAX function
        if (!refresh) {
            // Loading the initial content
            console.log('初始化完成');
        } else if (refresh && !next_page) {
            // Refreshing the content
            $('#list_info').html('');
            loadInfo($('#list_info'),1);
        } else if (refresh && next_page) {
            // Loading the next-page content and refreshing
            loadInfo($('#list_info'),next_page);
        }

        if (refresh) {
            myScroll.refresh();
            pullActionCallback();
        } else {
            if (myScroll) {
                myScroll.destroy();
                $(myScroll.scroller).attr('style', ''); // Required since the styles applied by IScroll might conflict with transitions of parent layers.
                myScroll = null;
            }
            trigger_myScroll();
        }
    }, 1000);
};

function loadInfo(e,next_page){
    var searchInfo;
    var list_info = $('#list_info');
    var value = $('#header_value').attr('data-value');
    var uri = '';
    var sort_type = $('#sort_type').val();
    if(sort_type != ''){
        uri += ('&sort_type='+sort_type);
    }
    var order_type = $('#order_type').val();
    if(order_type != ''){
        uri += ('&order_type='+order_type);
    }
    var filter = $('#filter').val();
    if(filter != ''){
        uri += ('&filter='+filter);
    }
    uri += '&access=xhr';
    $.ajax({
        url:'/search/'+ value + '?p='+ next_page + uri,
        type:'get',
        dataType:'json',
        beforeSend:function(){
            $('#last_load_li').text('正在加载中....');
        },
        success:function(msg){
            if(msg.code == 200) {
                searchInfo  = msg.search;
                if(searchInfo){
                    //组装li
                    var lis = '';
                    for(var j = 0; j < searchInfo.length; j++){
                        var image = searchInfo[j]['images']['thumb'];
                        var thumb = '/Public/images/no_drug_image.jpg';
                        if(image.length > 0){
                            thumb = image[0];
                        }
                        lis += '<li><a href="/drug/'+ searchInfo[j]['objectId'] +'" ><img src="' + thumb +'" class="pro-img"><p class="pro-deso"><span class="pro-tit"><span class="pro-bs">';
                        if(searchInfo[j]['base_drug']) {
                            lis += '<span class="pro-bs0 pro-bs2">基</span>';
                        }
                        if(searchInfo[j]['base_drug']) {
                            lis += '<span class="pro-bs0 pro-bs2">医保</span>';
                        }
                        if(searchInfo[j]['OTC'] == '甲'){
                            lis += '<span class="pro-bs0 pro-bs3">甲</span>'
                        }else if(searchInfo[j]['OTC'] == '乙'){
                            lis += '<span class="pro-bs0 pro-bs4">乙</span>'
                        }else{
                            lis += '<span class="pro-bs0 pro-bs1">处</span>'
                        }
                        if(searchInfo[j]['product_cate'] == '中药'){
                            lis += '<span class="pro-bs0 pro-bs4">中药</span>'
                        }else{
                            lis += '<span class="pro-bs0 pro-bs1">西药</span>'
                        }
                        lis += '</span>' + searchInfo[j]['product_name'] + '</span><span class="pro-star">';
                        for(var m=0; m < 5;m++){
                            if(m < parseInt(searchInfo[j]['score'])){
                                lis += '<i class="icon-iconfont-star1"></i>'
                            }else{
                                lis += '<i class="icon-iconfont-star2"></i>'
                            }
                        }
                        lis += searchInfo[j]['score'] +'分</span><span class="pro-info"><span class="pro-infof">'+ searchInfo[j]['price']['market'];
                        lis += '</span>'+ searchInfo[j]['instructions']['生产企业'] +'</span></p></a></li>';
                    }
                    $('#last_load_li').remove();
                    list_info.append(lis);
                    list_info.append('<li style="text-align: center;" id="last_load_li">加载更多...</li>')
                }else{
                    $('#last_load_li').text('没有更多了');
                }
            }else{
                searchInfo = [];
            }
        }
    });
}

function getSearchInfo(next_page){

}

function pullDownAction() {
    load_content('refresh');
    $('#list_info').data('page', 1);

    // Since "topOffset" is not supported with iscroll-5
    $('.scroller').css({top:0});

}
function pullUpAction(callback) {
    var next_page = 2;
    if ($('#list_info').data('page')) {
        next_page = parseInt($('#list_info').data('page'), 10) + 1;
    } else {
        next_page = 2;
    }
    load_content('refresh', next_page);
    $('#list_info').data('page', next_page);

    if (callback) {
        callback();
    }
}
function pullActionCallback() {
    if (pullDownEl && pullDownEl.className.match('loading')) {

        pullDownEl.className = 'pullDown';
        pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉刷新';

        myScroll.scrollTo(0, parseInt(pullUpOffset)*(-1), 200);

    } else if (pullUpEl && pullUpEl.className.match('loading')) {

        $('.pullUp').removeClass('loading').html('');

    }
}

var pullActionDetect = {
    count:0,
    limit:10,
    check:function(count) {
        if (count) {
            pullActionDetect.count = 0;
        }
        // Detects whether the momentum has stopped, and if it has reached the end - 200px of the scroller - it trigger the pullUpAction
        setTimeout(function() {
            if (myScroll.y <= (myScroll.maxScrollY + 200) && pullUpEl && !pullUpEl.className.match('loading')) {
                $('.pullUp').addClass('loading').html('<span class="pullUpIcon">&nbsp;</span><span class="pullUpLabel">正在加载...</span>');
                pullUpAction();
            } else if (pullActionDetect.count < pullActionDetect.limit) {
                pullActionDetect.check();
                pullActionDetect.count++;
            }
        }, 200);
    }
}

function trigger_myScroll(offset) {
    pullDownEl = document.querySelector('#wrapper .pullDown');
    if (pullDownEl) {
        pullDownOffset = pullDownEl.offsetHeight;
    } else {
        pullDownOffset = 0;
    }
    pullUpEl = document.querySelector('#wrapper .pullUp');
    if (pullUpEl) {
        pullUpOffset = pullUpEl.offsetHeight;
    } else {
        pullUpOffset = 0;
    }

    if ($('#wrapper ul > li').length < items_per_page) {
        // If we have only 1 page of result - we hide the pullup and pulldown indicators.
        $('#wrapper .pullDown').hide();
        $('#wrapper .pullUp span').hide();
        offset = 0;
    } else if (!offset) {
        // If we have more than 1 page of results and offset is not manually defined - we set it to be the pullUpOffset.
        offset = pullUpOffset;
    }

    myScroll = new IScroll('#wrapper', {
        probeType:1, tap:true, click:false, preventDefaultException:{tagName:/.*/}, mouseWheel:true, scrollbars:true, fadeScrollbars:true, interactiveScrollbars:false, keyBindings:false,
        deceleration:0.0002,
        startY:(parseInt(offset)*(-1))
    });

    myScroll.on('scrollStart', function () {
        scroll_in_progress = true;
    });
    myScroll.on('scroll', function () {

        scroll_in_progress = true;

        if ($('#wrapper ul > li').length >= items_per_page) {
            if (this.y >= 5 && pullDownEl && !pullDownEl.className.match('flip')) {
                pullDownEl.className = 'pullDown flip';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '松开显示';
                this.minScrollY = 0;
            } else if (this.y <= 5 && pullDownEl && pullDownEl.className.match('flip')) {
                pullDownEl.className = 'pullDown';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉刷新';
                this.minScrollY = -pullDownOffset;
            }

            pullActionDetect.check(0);

        }
    });
    myScroll.on('scrollEnd', function () {
        setTimeout(function() {
            scroll_in_progress = false;
        }, 100);
        if ($('#wrapper ul > li').length >= items_per_page) {
            if (pullDownEl && pullDownEl.className.match('flip')) {
                pullDownEl.className = 'pullDown loading';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '正在加载...';
                pullDownAction();
            }
            // We let the momentum scroll finish, and if reached the end - loading the next page
            pullActionDetect.check(0);
        }
    });

    // In order to prevent seeing the "pull down to refresh" before the iScoll is trigger - the wrapper is located at left:-9999px and returned to left:0 after the iScoll is initiated
    setTimeout(function() {
        $('#wrapper').css({left:0});
    }, 100);
}

function loaded() {

    load_content();

}

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
